<?php

namespace platform;
use GuzzleHttp\Client;
use redis\RedisTools;
use think\facade\Log;


/**
 * 东传公众号
 */
class DcPlatform
{
    public static $channel = '92d585c9fc1b43356bf99250a2ll15h';
    public static $url = 'https://api.drumplus.cn/api/wechat/get_wechat';
    public static $key = '@JLKKsdsdf6+5*&msad';


    /**
     * 获取关注公众号的二维码
     */
    public function queryInterface($user)
    {
        $s = rand(1,100) < 70 ? 2 : 1;
        $sex = $s;//$user['sex']==0?$s:$user['sex'];
        $time = time();
        $k = self::$key;
        $response_message = md5("{$user['id']}{$k}{$time}");
        $data = [
            'sex'=>$sex,
            'province'=>'广东省',
//            'city'=>'深圳市',
            'openid'=>$user['unionid'],
            'channel'=>self::$channel,
            'nickname'=>$user['nickname'],
            'response_message'=>$response_message
        ];
        $http = new Client(['headers' => [
            "Content-type" => 'application/json'
        ]]);
        $response = $http->post(self::$url, [
            'json' => $data
        ]);
        //返回值
        if($response->getStatusCode() != 200){
            throw new \Exception("网络请求错误");
        }
        $data = $response->getBody()->getContents();
        Log::write($data, '东传公众号返回信息');
        $data = json_decode($data,true);

        if($data['code'] != 200){
            throw new \Exception("获取失败");
        }
        //设置请求数据缓存
        $oRedis = RedisTools::getInstance(config('cache.stores.redis'), 0)->getRedis();
        $times = $time+1800;
        $h = date('H',$times);
        $i = date('i',$times);
        $s = date('s',$times);
        $expireTime=mktime($h,$i,$s,date("m"),date("d"),date("Y"));
        $key = 'dc:'.$response_message;
        $oRedis->set($key,$user['unionid']);
        $oRedis->expireAt($key,$expireTime);
        return $data['wechat'];
    }

    /**
     * 异步通知
     * @param $data
     */
    public function notify($data)
    {
        if(!isset($data['channel'])) return 'error';
        if(!isset($data['subscribe'])) return 'error';
        if(!isset($data['appid'])) return 'error';
        if(!isset($data['appname'])) return 'error';
        if(!isset($data['subscribe'])) return 'error';
        if($data['channel'] != self::$channel) return 'error';
        $response_message = $data['response_message'];
        $oRedis = new RedisLock();
        $oRedis->setRedis('tests',"tests",1200);
        $uid = $oRedis->getRedis($response_message);
        if(!$uid) return 'error';
        $user = User::where('uid','=',(int)$uid)->find();
        if($data['subscribe'] == 1){
            if($data['fansType'] != 1) return 'success';
            //关注事件，处理用户积分加减
            $num = 10;
            Db::startTrans();
            try {
                if($num > 0){
                    $UserBillRes = UserBill::create([
                        'uid'=>$uid,
                        'pm'=>1,
                        'title'=>'关注公众号',
                        'category'=>'integral',
                        'type'=>'dc_follow_account',
                        'number'=>$num,
                        'mark'=>'关注公众号',
                        'add_time'=>time(),
                        'balance' => (float)$user['integral']
                    ]);
                    if(!$UserBillRes) throw new Exception('更新用户奖励记录失败1');
                }
                if($num > 0){
                    //更新用户资金账户
                    $UserRes = User::where('uid','=',$uid)->update(['integral'=>$user['integral']+$num]);
                    if(!$UserRes) throw new Exception('更新用户'.$uid.'账户失败');
                }
                Db::commit();
                //删除redis数据
                $oRedis->delRedis($response_message);
                return 'success';
            }catch (Exception $exception){
                // 回滚事务
                Db::rollback();
                return 'error';
            }
        }
    }
}